import { Popover, Form, Button, Input, Checkbox, message } from 'antd';
import { PlusCircleOutlined, EditOutlined } from '@ant-design/icons';
import { useState, useEffect } from 'react';
import { connect } from 'react-redux';
import Cookies from 'js-cookie';
import { deepClone, validateIDCard } from '@/utils';
// 样式
import styles from '@/styles/ShoppingCart.module.scss';
import ordetStyles from '@/styles/CommonOrder.module.scss';
// api
import { addCustomer } from '@/api/order';
import { getCustomerList } from '@/store/actions/cart';

// fn：联系人信息
function setContactToStorage (params){
    sessionStorage.setItem('contact', JSON.stringify(params));
}

// Component：联系人组件
const OrderForm = ({ _getCustomerList, cart: { contactData, customerList } }) => {

    const userInfo = JSON.parse(Cookies.get('userInfo') || "{}");

    const [form] = Form.useForm();
    const { name } = contactData;

    const [updateId, setUpdateId] = useState('');
    const [contact, setContact] = useState('');
    const [telephone, setPhone] = useState(userInfo?.phone);
    const [customers, setCustomers] = useState([]);

    useEffect(() => {
        setContact(name);
    }, [contactData]);

    useEffect(() => {
        const _customers = deepClone(customerList);
        setCustomers([..._customers]);
    }, [customerList]);

    // 新增/修改游客信息
    function onAddFormFinish(values) {
        const { contact, idcard, telphone } = values;
        let params = {
            id: updateId,
            idCard: idcard,
            name: contact,
            phoneNum: telphone || userInfo?.phone,
            ticketType: "",
            ticketTypeDesc: "",
        }
        addCustomer(params).then(res => {
            const { code } = res;
            if (code === 0) {
                message.success('操作成功');
                _getCustomerList();
                !updateId && form.resetFields();
            }
        })
    }
    // 修改游客信息，填充form表单
    function updateCustomer(data) {
        const { id = "", name = "", idCard = "", phoneNum = "" } = data;
        form.setFieldsValue({
            contact: name,
            idcard: idCard,
            telphone: phoneNum
        });
        setUpdateId(id);
    }
    // 选择实名游客
    function selectCustomer(data) {
        const { name } = data;
        setContact(name);
        setContactToStorage({name, phoneNum: userInfo?.phone});
    }

    // onChangeFn
    function onChangeContact (val){
        setContact(val);
        setContactToStorage({name: val, phoneNum: userInfo?.phone});
    }
    function onChangePhone (val){
        setPhone(val);
        setContactToStorage({name, phoneNum: val});
    }

    // Component: 新增游客信息，form表单弹出框
    const popFillForm = (
        <section className={ordetStyles['fill-form']}>
            <h3>添加/修改信息</h3>
            <Form
                form={form}
                onFinish={onAddFormFinish}
                autoComplete="off"
            >
                <Form.Item
                    label="联系人"
                    name="contact"
                    rules={[{ required: true, message: '请输入姓名' }]}
                >
                    <Input placeholder="请输入姓名" />
                </Form.Item>
                <Form.Item
                    label="身份证号"
                    name="idcard"
                    rules={[
                        { required: true, message: '请输入身份证号' },
                        {
                            validator: (rules, value, callback) => {
                                const { status, msg } = validateIDCard(value);
                                !status ? callback(msg) : callback()
                            }
                        }
                    ]}
                >
                    <Input placeholder="请输入身份证号" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        </section>
    )
    // Component: 选择游客信息
    const popSelectForm = (
        <section className={ordetStyles['fill-select']}>
            <Popover placement="rightTop" trigger="click" content={popFillForm} >
                <button className={ordetStyles['fill-btn']} onClick={() => { updateCustomer({}) }}>
                    <PlusCircleOutlined /> 添加游客
                </button>
            </Popover>
            <h3>选择游客信息</h3>
            {
                customers.length ?
                    customers.map((item) => {
                        return (
                            <dl key={item.id}>
                                <dd onClick={() => { selectCustomer(item) }}>
                                    <Checkbox checked={item.checked} />
                                </dd>
                                <dd>{item.name}</dd>
                                <dd>{item.idCard}</dd>
                                <dd>
                                    <Popover placement="rightTop" trigger="click" content={popFillForm} >
                                        <EditOutlined onClick={() => { updateCustomer(item) }} />
                                    </Popover>
                                </dd>
                            </dl>
                        )
                    }) : <p>暂无游客信息</p>
            }
        </section>
    )
    
    return (
        <div className={styles['fill-info']}>
            <span className={styles['label']}>联系人：</span>
            <Input
                placeholder="请输入姓名"
                value={contact}
                onChange={(e) => onChangeContact(e.target.value)}
            />
            <span className={styles['label']}>手机号：</span>
            <Input
                placeholder="请输入手机号"
                value={telephone}
                onChange={(e) => onChangePhone(e.target.value)}
            />
            <Popover placement="topLeft" trigger="click" content={popSelectForm}>
                <Button type="primary">选择出行人</Button>
            </Popover>
        </div>
    )
}

const mapStateToProps = state => {
    return {
        cart: state.cart
    }
}
const mapDispatchToProps = dispatch => {
    return {
        _getCustomerList: v => dispatch(getCustomerList(v)),
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(OrderForm)